// 不做mysql，json
// const fs = require('fs')
const Koa = require('koa')
const router = require('koa-router')();
const MainData = require('./Data/mainData/MainData.json')
const SortData = require('./Data/sortData/SortData.json')
const app = new Koa()
const cors = require('koa2-cors')
const Mock = require('mockjs')
const Random = Mock.Random

app.use(cors({
    origin: function(ctx) { //设置允许来自指定域名请求
        // if (ctx.url === '/test') {
        return '*'; // 允许来自所有域名请求
        // }
        // return 'http://localhost:3000'; //只允许http://localhost:8080这个域名的请求
    },
    maxAge: 5, //指定本次预检请求的有效期，单位为秒。
    credentials: true, //是否允许发送Cookie
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], //设置所允许的HTTP请求方法
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'], //设置服务器支持的所有头信息字段
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] //设置获取其他自定义字段
}))

app
    .use(router.routes())
    .use(router.allowedMethods())

router.get('/home/main', async (ctx) => {
    ctx.response.body = {
        success: true,
        data: MainData
    }
})

router.get('/home/sort',async (ctx) => {
    ctx.response.body = {
        success: true,
        data: SortData
    }
})

router.get('/home/list',async (ctx) => {
    let { limit = 20, page = 2 } = ctx.request.query
    console.log(limit,page,'.....');
    let data = Mock.mock({
        'list|20': [{
            'id': '@increment',
            'tag': '年货节',
            'title': '@ctitle(20)',
            'mark': '新人专享',
            'label': '购买',
            'commont': '3248',
            // 'imgsrc': Random.image('140x120'),
            'imgsrc': 'https://i0.hdslb.com/bfs/article/6566aa6e4cff58791dc94d586bd4de5b2c89bbed.jpg@942w_1295h_progressive.webp',
            'price': '@float(20,2)',
            'lock': '限一份'
        }]
    })

    ctx.body = {
        success: true,
        data
    }
})

router.get('/home/sortList',async (ctx) => {
    let { limit = 20, page = 2 } = ctx.request.query
    console.log(limit,page,'.....');
    let data = Mock.mock({
        'sortList|20': [{
            'id': '@increment',
            'tag': '大降价',
            'title': '@ctitle(5,7)',
            'mark': '特惠专区',
            'label': '下单',
            'commont': '3248',
            // 'imgsrc': Random.image('140x120'),
            'imgsrc': 'https://i0.hdslb.com/bfs/article/6566aa6e4cff58791dc94d586bd4de5b2c89bbed.jpg@942w_1295h_progressive.webp',
            'price': '19.9',
            'lock': '限一份'
        }]
    })

    ctx.body = {
        success: true,
        data
    }
})

// 1.http服务
// 2.简单路由模块
// 3.cors
// 4.返回数据

app.listen(8080, () => {
    console.log('server is running 8080');
})